package asynchronous_service

import (
	"duoke/context"
	"duoke/model"
	"duoke/service"
	"duoke/service/asynchronous"
	"duoke/tables"
	utils "duoke/utils/common"
	"duoke/utils/gconv"
	"duoke/utils/gjson"
	"duoke/utils/orm"
	"duoke/utils/redislib"
	"errors"
	"github.com/gin-gonic/gin"
	"time"
)

var User = new(userService)

type userService struct{}

// Batches 提现异步
func (s *userService) Batches(c *gin.Context, id int) error {
	var withdrawal tables.Withdrawal
	get, err := orm.Db.ID(id).Table("withdrawal").Get(&withdrawal)
	if !get || err != nil {
		return errors.New("提现信息不存在")
	}
	if withdrawal.FreezeAmount == 0 {
		return errors.New("已提现")
	}
	user, err := service.User.GetById(c, withdrawal.UserId, "*")
	if err != nil {
		return errors.New("获取用户信息失败")
	}
	stream, err := redislib.NewRedisStream(redislib.Redis,
		"batches", "notifications_group", "batches_1")
	if err != nil {
		return errors.New("提现id")
	}
	separateService := asynchronous.NewSeparateService(stream)
	go func() {
		separateService.StartListening(c)
	}()
	time.AfterFunc(2*time.Second, func() {
		// 绑定分账用户
		order := utils.Common.GetOrder()
		message := map[string]interface{}{
			"type": "batches",
			"content": gjson.StructOrMap2Json(&model.Transfer{
				OutBillNo:       order,
				UserId:          user.Id,
				Avatar:          user.Avatar,
				WithdrawalId:    id,
				TransferSceneId: "1000",
				Openid:          user.Openid,
				TransferAmount:  gconv.Int(withdrawal.FreezeAmount * 100),
				TransferRemark:  "用户提现",
				NotifyUrl:       context.Global.Domain + "/mp/notify/withdrawal",
				TransferSceneReportInfos: []map[string]interface{}{
					{
						"info_type":    "活动名称",
						"info_content": "用户提现",
					},
					{
						"info_type":    "奖励说明",
						"info_content": "用户获取提现金额",
					},
				},
			}),
		}
		separateService.SendNotification(message)
	})
	return nil
}
